package _dp_base;

/**
 * 1143. 最长公共子序列
 */
public class No1143 {
    private String text1, text2;

    /**
     * 1. 递归
     */
    public int longestCommonSubsequence1(String text1, String text2) {
        this.text1 = text1;
        this.text2 = text2;
        int n = text1.length();
        int m = text2.length();
        return dfs(n - 1, m - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return 0;
        else if (text1.charAt(i) == text2.charAt(j)) return dfs(i - 1, j - 1) + 1;
        else return Math.max(dfs(i - 1, j), dfs(i, j - 1));
    }

    /**
     * 2. 迭代
     */
    public int longestCommonSubsequence2(String text1, String text2) {
        int n = text1.length();
        int m = text2.length();
        int[][] f = new int[n + 1][m + 1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (text1.charAt(i) == text2.charAt(j)) f[i + 1][j + 1] = f[i][j] + 1;
                else f[i + 1][j + 1] = Math.max(f[i][j + 1], f[i + 1][j]);
            }
        }
        return f[n][m];
    }

    /**
     * 3. 滚动数组
     */
    public int longestCommonSubsequence3(String text1, String text2) {
        int n = text1.length();
        int m = text2.length();
        int[][] f = new int[2][m + 1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (text1.charAt(i) == text2.charAt(j)) f[(i + 1) % 2][j + 1] = f[i % 2][j] + 1;
                else f[(i + 1) % 2][j + 1] = Math.max(f[i % 2][j + 1], f[(i + 1) % 2][j]);
            }
        }
        return f[n % 2][m];
    }

    /**
     * 4. 一维数组
     */
    public int longestCommonSubsequence4(String text1, String text2) {
        int n = text1.length();
        int m = text2.length();
        int[] f = new int[m + 1];
        for (int i = 0; i < n; i++) {
            int pre = f[0];
            for (int j = 0; j < m; j++) {
                int temp = f[j + 1];
                if (text1.charAt(i) == text2.charAt(j)) f[j + 1] = pre + 1;
                else f[j + 1] = Math.max(f[j + 1], f[j]);
                pre = temp;
            }
        }
        return f[m];
    }
}
